package com.example.stickyheaderdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerview;
    private TextView mTvTop;


    /**
     * 浮动标题的高度
     */
    private int mTopBarHeight = 0;
    /**
     * 当前可见的第一个item的下标
     */
    private int mCurrentPosition = 0;
    /**
     * 线性管理器
     */
    private LinearLayoutManager linearLayoutManager;
    /**
     * 数据源
     */
    private ArrayList<String> mList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerview.setLayoutManager(linearLayoutManager);
        mRecyclerview.setAdapter(new MyRecyclerViewAdapter(this, mList));
        mRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //获取上浮title的高度
                mTopBarHeight = mTvTop.getHeight();

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //当滑动的时候获取当前滑动的下一个item的视图
                View view = linearLayoutManager.findViewByPosition(mCurrentPosition + 1);
                if (view == null) {
                    return;
                }
                //当view距离手机顶端的top值小于等于浮动title的高度的时候
                if (view.getTop() <= mTopBarHeight) {
                    //浮动标题的高度-view距离top的距离，计算出view和浮动层的交集部分，
                    //然后设置浮动view的top值，保证滑动的view始终是在浮动层的下方
                    mTvTop.setY(-(mTopBarHeight - view.getTop()));
                } else {
                    mTvTop.setY(0);
                }

                if (mCurrentPosition != linearLayoutManager.findFirstVisibleItemPosition()) {
                    mCurrentPosition = linearLayoutManager.findFirstVisibleItemPosition();
                    mTvTop.setY(0);
                    mTvTop.setText(mList.get(mCurrentPosition));
                }
            }
        });

    }

    private void initView() {
        mRecyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        mTvTop = (TextView) findViewById(R.id.tv_top);
        mList = new ArrayList<>();


        for (int i = 0; i < 20; i++) {
            mList.add("选项===>>" + i);
        }
    }
}
